<template>
  <q-dialog v-model="show" persistent>
    <q-card class="dialog-content halt-detail" style="min-width: 400px; max-height: 500px">
      <q-card-section class="dialog-title bg-primary" >
        <div class="text-center text-white dialog-title">
          <span class="font-size-16">
            修改停机原因
          </span>
        </div>
      </q-card-section>
      <q-form @submit="submit" greedy class="q-gutter-md dialog-content">
        <q-card-section>
          <q-select
            class="input-select"
            v-model="stopType"
            outlined
            :options="stopTypeList"
            @input="changeType()"
            dense
            options-dense
            emit-value
            map-options
            :rules="[val => val !== null || '请选择停机原因类型']"
          >
            <template v-slot:no-option>
              <div class="no-option"/>
            </template>
            <template v-slot:before>
              <label class="text-right name label-width">
                <span class="text-red">*</span>
                <span>停机类型:</span>
              </label>
            </template>
          </q-select>
          <q-select
            class="input-select"
            v-model="stopCause"
            outlined
            :options="stopCauseList"
            dense
            options-dense
            emit-value
            map-options
            :rules="[val => val !== null || '请选择停机原因']"
          >
            <template v-slot:no-option>
              <div class="no-option"/>
            </template>
            <template v-slot:before>
              <label class="text-right name label-width">
                <span class="text-red">*</span>
                <span>停机原因:</span>
              </label>
            </template>
          </q-select>
          <select-tree label="所在部门" :sel-tree="selDepartment" ref="selectTree"
                       :tree-list="departments" node-key="id"
                       @treeChange="_changeTreeNode" />
          <q-select
            class="input-select"
            v-model="operatorId"
            outlined
            :options="userList"
            dense
            options-dense
            emit-value
            map-options
          >
            <template v-slot:no-option>
              <div class="no-option"/>
            </template>
            <template v-slot:before>
              <label class="text-right name label-width">
                <span>停机人员:</span>
              </label>
            </template>
          </q-select>
          <q-input outlined v-model="remark" type="textarea" counter autogrow maxlength="100" class="margin-t-20">
            <template v-slot:before>
              <label class="text-right name">备注信息:</label>
            </template>
          </q-input>
        </q-card-section>
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" @click="$emit('close')" class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit" :loading="submitting"/>
        </div>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script>
import { getCauseItem, getCauseTypeList } from '../../../boot/system/reason'
import { editDowntimeDuration } from '../../../boot/status/machine'
import userManageApi from '../../../boot/system/user-manage'
// import { getOrganize } from '../../../boot/tpm/equipment-record'
// import { defaultSchemesClearer } from '../../../assets/js/util'
import SelectTree from 'src/components/select-tree'
import { putBatchReport } from '../../../boot/statistics/stop-stat'

export default {
  name: 'edit-detail',
  props: {
    show: {
      type: Boolean,
      default: false,
      required: true
    },
    data: {
      required: true
    },
    selectedReport: Array,
    isReports: {
      type: Boolean,
      default: false
    },
    isFilter: {
      type: Boolean
    }
  },
  components: {
    SelectTree
  },
  data () {
    return {
      boxId: null,
      submitting: false,
      stopType: null,
      stopTypeDetail: {},
      stopTypeList: [], // 停机原因类型
      stopCause: null,
      stopCauseList: [],
      stopCauseDetail: {},
      remark: '',
      operatorId: null,
      userDetail: {},
      userList: [], // 用户
      selDepartment: {}, // 所在位置
      departments: [] // 部门列表
    }
  },
  created () {
    this.getStopcauseList()
    this.getDepartmentsTree()
  },
  methods: {
    _changeTreeNode (val) {
      if (val.id && val.label) {
        this.selDepartment.id = val.id
        this.selDepartment.level = val.level
        this.selDepartment.label = val.label
        this.listUsers(true)
      }
    },
    // 修改停机原因
    changeType () {
      this.getCauseItem(this.stopType, true)
    },
    /**
     * 列举用户
     */
    listUsers: function (isChange) {
      this.userList = []
      const queryParams = {
        departmentId: this.selDepartment.id
      }
      if (!this.data.operatorId) {
        this.userList[0] = {
          value: null,
          label: '--'
        }
      } else {
        if (!isChange) {
          this.operatorId = this.data.operatorId
        }
      }
      userManageApi.listUsersNoPage(queryParams).then(res => {
        // console.log(res, 'userList')
        res.list.forEach(o => {
          // 人员map（为取人员名）
          this.userDetail[o.id] = o.name
          this.userList.push({
            value: o.id,
            label: o.name
          })
        })
        if (isChange) {
          this.operatorId = this.userList[0].value
        }
      })
    },
    /**
     * 获取部门 tree
     */
    getDepartmentsTree: function () {
      userManageApi.getDepartmentsTree().then(res => {
        let departments = res.filter(item => item.type !== 'cc' && item.type !== 'cg')
        this.departments = departments
      })
    },
    // 获取原因类型列表
    getStopcauseList () {
      getCauseTypeList(3, this.isFilter).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            // 让步原因类型map（为取让步名）
            this.stopTypeDetail[o.id] = o.label
            this.stopTypeList.push({
              value: o.id,
              label: o.label
            })
          })
          if (!this.data && !this.data.typeId) {
            if (res.data[0]) {
              this.stopType = res.data[0].id
            }
          }
          this.getCauseItem(this.stopType, false)
        }
      })
    },
    // 根据停机原因类型代码查询停机原因
    getCauseItem (typeId, isChange) {
      const params = {
        id: typeId,
        showDisable: false
      }
      this.stopCauseList = []
      this.stopCauseDetail = {}
      this.stopCause = ''
      getCauseItem(params).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(o => {
            this.stopCauseDetail[o.id] = o.label
            this.stopCauseList.push({
              value: o.id,
              label: o.label
            })
            if (!this.data.causeId && !isChange && o.id === this.data.causeId) {
              this.stopCause = o.id
            }
          })
          if (isChange) {
            this.stopCause = res.data[0].id
          }
        } else {
          this.stopCause = null
        }
      })
    },
    submit () {
      let params = {
        timeStamp: this.data.timeStamp,
        typeId: this.stopType,
        type: this.stopTypeDetail[this.stopType],
        causeId: this.stopCause,
        cause: this.stopCauseDetail[this.stopCause],
        remark: this.remark
      }
      if (this.operatorId) {
        params['operatorId'] = this.operatorId
        params['operatorName'] = this.userDetail[this.operatorId]
        params['deptId'] = this.selDepartment.id
      }
      if (this.isReports) {
        const timeStamp = this.selectedReport.map(v => v.timeStamp)
        const list = []
        for (let i = 0; i < timeStamp.length; i++) {
          params.timeStamp = timeStamp[i]
          list.push({ ...params })
        }
        putBatchReport(list).then(res => {
          if (res.code === '1200') {
            this.$q.dialog({
              title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53" ></i> 编辑成功</p>`,
              html: true,
              ok: {
                unelevated: true,
                label: '确认'
              }
            })
              .onOk(() => {
                this.$emit('getList')
                this.$emit('close')
              })
          }
        })
      } else {
        editDowntimeDuration(this.boxId, params).then(res => {
          if (res.code === '1200') {
            this.$q.dialog({
              title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53" ></i> 编辑成功</p>`,
              html: true,
              ok: {
                unelevated: true,
                label: '确认'
              }
            })
              .onOk(() => {
                this.$emit('getList')
                this.$emit('close')
              })
          }
        })
      }
    },
    reorganize (node) {
      if (node.id === this.data.deptId) {
        this.selDepartment.id = node.id
        this.selDepartment.level = node.level
        this.selDepartment.label = node.label
      }

      if (node.children instanceof Array && !this.selDepartment.id) {
        node.children.forEach(this.reorganize)
      }
    }
  },
  watch: {
    show (val) {
      if (val) {
        this.boxId = this.data.boxId
        this.remark = this.data.remark
        if (this.data.typeId) {
          this.stopType = this.data.typeId
        } else {
          this.stopType = this.stopTypeList.length > 0 ? this.stopTypeList[0].value : null
        }
        if (this.data.causeId) {
          this.stopCause = this.data.causeId
        }
        this.getCauseItem(this.stopType, true)
        if (this.data.operatorId) {
          this.selDepartment.id = null
          // 确定部门所在位置
          this.departments.forEach(this.reorganize)
          this.listUsers()
        } else {
          this.selDepartment.id = this.departments[0].id
          this.selDepartment.level = this.departments[0].level
          this.selDepartment.label = this.departments[0].label
          this.operatorId = null
          this.listUsers()
        }
        this.$nextTick(() => {
          this.$refs.selectTree.setValue(this.selDepartment)
        })
      }
    }
  }
}
</script>

<style scoped lang="stylus">

</style>
